package com.xywy.common.net;

import android.content.Context;

import com.xywy.common.constants.ResultCode;
import com.xywy.common.util.CalendarUtil;
import com.xywy.common.util.MLog;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 名称: Parser
 * 描述: 网络解析基类
 *
 * @author Joker
 */

public class Parser implements Serializable {

    private static final long serialVersionUID = 2769575380894472597L;
    /**
     * 设置参数
     * action,map,context为请求必须参数，back为请求返回参数,request 标记请求类型,默认是post
     */
    public String action = null;    //请求路径
    public HashMap<String, Object> map = null;  //请求参数
    public List<NameValuePair> nameValuePair = null;
    public String url = "";
    public Boolean ifFilter = true;   //是否过滤空

    /**
     * 是否弹出Toast,Progress,默认不显示
     */
    public Boolean isShowProgress = false;
    /**
     * context需要一个activity
     */
    public Context context = null;
    // 返回数据json字符串，需要手动转换json
    public String back = null;
    public boolean sns = false;
    /**
     * get请求，或post请求，或upload
     */
    public String request = "post";
    public String TAG = ((Object) this).getClass().getSimpleName();
    public int statusCode; // 状态码
    /**
     * 用于过滤多次请求
     */
    public boolean filter = false;

    /**
     * 将服务端返回的数据分别在 实现类中 封装到对应的对象中
     *
     * @param t
     * @return 具体对象
     */
    public <T> T parser(T t) {
        return null;
    }

    /**
     * 返回数据中的result值
     *
     * @return 当不包含或返回为null时, 返回-1
     */
    public int getResult() {
        int code = 0;
           if (back != null && back.length() != 0) {
                JSONObject json = null;
                try {
                        json = new JSONObject(back);
                    } catch (JSONException e) {
                        e.printStackTrace();
                }
                if(json==null)
                	return -1;
                if (json.isNull("state"))
                    return -1;
                if (json.optInt("state") == ResultCode.SUCCESS) {
                    code = json.optInt("state");
                }
             }else{
               return -1;
             }

        return code;
    }

    /**
     * 服务端返回json
     */
    public JSONObject retBackJson() {
        JSONObject json = new JSONObject();
        if (back != null && back.length() != 0) {
            try {
                json = new JSONObject(back);
                MLog.i(TAG, "json解析===retBackJson =="+json.toString());
            } catch (JSONException e) {
                MLog.e(TAG, "json解析", e);
            }
        }
        return json;
    }

    /**
     * 用于判断两个paser是否是同一个
     *
     * @return
     */
    public boolean compareTo(Object o) {
        if (o instanceof Parser) {
        } else {
            return false;
        }

        Parser paser = (Parser) o;
        //首先判断接口
        if (paser.action != action) {
            return false;
        }

        //其次判断请求类型
        if (!paser.request.equalsIgnoreCase(request)) {
            return false;
        }

        //匹配请求参数
        if (paser.map == null && map == null) {
            if (nameValuePair != null && paser.nameValuePair != null) {
                int tmp = nameValuePair.size();
                if (tmp != paser.nameValuePair.size()) {
                    return false;
                }
                for (int i = 0; i < tmp; i++) {
                    if (!nameValuePair.get(i).equals(paser.nameValuePair.get(i))) {
                        return false;
                    }
                }
            }
        } else {
            int tmp = map.size();
            if (paser.map.size() != tmp) {
                return false;
            }
            Set<String> key1 = map.keySet();
            Set<String> key2 = paser.map.keySet();
            if (!key1.containsAll(key2)) {
                MLog.i(TAG, "key不一样");
                return false;
            }
            Set<Object> value1 = new HashSet<Object>();
            Set<Object> value2 = new HashSet<Object>();

            Iterator iterator1 = key1.iterator();
            Iterator iterator2 = key2.iterator();
            while (iterator1.hasNext() && iterator2.hasNext()) {
                value1.add(map.get(iterator1.next()));
                value2.add(map.get(iterator2.next()));
            }
            if (!value1.containsAll(value2)) {
                MLog.i(TAG, "value不一样");
                return false;
            }
        }
        return true;
    }

    @Override
    public String toString() {
        String time = CalendarUtil.convertToYYYYMMDDHHMMSS(new Date());
        if (map == null)
            map = new HashMap<String, Object>();
        return "\n" + "BasePaser{" +
                "time='" + time + '\'' +
                "action='" + action + '\'' +
                ", map=" + map.entrySet() +
                ", nameValuePair=" + nameValuePair +
                ", url='" + url + '\'' +
                ", context=" + context +
                ", back='" + back + '\'' +
                ", sns=" + sns +
                ", request='" + request + '\'' +
                ", TAG='" + TAG + '\'' +
                ", statusCode=" + statusCode +
                ", filter=" + filter +
                '}';
    }
}
